package com.af.security.auth.user.detail;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author : zhenyun.su
 * @since : 2020/03/26
 */

public class AfUserDetails implements UserDetails {
    private static final long serialVersionUID = 4129386981414615632L;

    private AuthUser authUser;
    private String password;
    private List<String> permitCodes;
    private List<AuthRole> authRoles;
    private List<AuthMenu> authMenus;

    public AfUserDetails(AuthUser authUser, String password, List<String> permitCodes, List<AuthRole> authRoles, List<AuthMenu> authMenus) {
        this.authUser = authUser;
        this.password = password;
        this.permitCodes = permitCodes;
        this.authRoles = authRoles;
        this.authMenus = authMenus;
    }

    /**
     * @comment : 加载授权信息，包含角色和功能点
     * 角色格式： role_角色, 比如： role_admin, role_user
     * 功能点格式: 资源_操作， 比如： user_list, user_create等等
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String code : permitCodes) {
            if (!StringUtils.isEmpty(code)) {
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        return authorities;
    }

    /**
     * @comment : 用户信息
     */
    public AuthUser getAuthUser() {
        return authUser;
    }
    /**
     * @comment : 角色列表
     */
    public List<AuthRole> getAuthRoles() {
        return authRoles;
    }
    /**
     * @comment : 菜单列表
     */
    public List<AuthMenu> getAuthMenus() {
        return authMenus;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return authUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return authUser.getAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return authUser.getAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return authUser.getCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return authUser.getEnabled();
    }
}
